package com.yaorange.teaching.service.impl;

import java.util.List;

import com.yaorange.common.security.utils.SecurityUtils;
import com.yaorange.system.api.domain.SysUser;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.yaorange.teaching.mapper.YaStudentMapper;
import com.yaorange.system.api.RemoteUserService;
import com.yaorange.teaching.domain.YaStudent;
import com.yaorange.teaching.service.IYaStudentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-08
 */
@Service
public class YaStudentServiceImpl implements IYaStudentService
{
    public static final String DEFAULT_PASSWORD = "123456";
    @Autowired
    private YaStudentMapper yaStudentMapper;
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询学生信息
     *
     * @param id 学生信息主键
     * @return 学生信息
     */
    @Override
    public YaStudent selectYaStudentById(Long id)
    {
        return yaStudentMapper.selectYaStudentById(id);
    }

    /**
     * 查询学生信息列表
     *
     * @param yaStudent 学生信息
     * @return 学生信息
     */
    @Override
    public List<YaStudent> selectYaStudentList(YaStudent yaStudent)
    {
        return yaStudentMapper.selectYaStudentList(yaStudent);
    }

    /**
     * 新增学生信息
     *
     * @param yaStudent 学生信息
     * @return 结果
     */
    @Override
//    @Transactional(transactionManager = "transactionManager")
    @GlobalTransactional
    public synchronized int insertYaStudent(YaStudent yaStudent)
    {
        //1.fegin远程访问系统微服务创建账号，并且返回user_id
        SysUser sysUser = new SysUser();
        sysUser.setNickName(yaStudent.getName());
        sysUser.setUserName(yaStudent.getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(DEFAULT_PASSWORD));

        Long userId = remoteUserService.registerStudent(sysUser).getData();
        //2.设置学生主键为user_id
        yaStudent.setId(userId);
        int i = 10/0;
        //3.保存到数据库
        return yaStudentMapper.insertYaStudent(yaStudent);
    }

    /**
     * 修改学生信息
     *
     * @param yaStudent 学生信息
     * @return 结果
     */
    @Override
    public int updateYaStudent(YaStudent yaStudent)
    {
        return yaStudentMapper.updateYaStudent(yaStudent);
    }

    /**
     * 批量删除学生信息
     *
     * @param ids 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteYaStudentByIds(Long[] ids)
    {
        return yaStudentMapper.deleteYaStudentByIds(ids);
    }

    /**
     * 删除学生信息信息
     *
     * @param id 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteYaStudentById(Long id)
    {
        return yaStudentMapper.deleteYaStudentById(id);
    }
}
